import React, {useEffect, useState} from 'react';
import {listChartByPageUsingPost} from "@/services/hjbi/chartController";
import {Avatar, Card, List, message, Result} from "antd";
import ReactECharts from "echarts-for-react";
import {useModel} from "@umijs/max";
import Search from "antd/es/input/Search";


const MyChart: React.FC = () => {

  const initSearchParams = {
    pageSize: 2,
    current: 1,
    sortField: 'createTime',
    sortOrder: 'descend',
  }

  const {initialState} = useModel('@@initialState')
  const {currentUser} = initialState ?? {}
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({...initSearchParams})
  const [chartList, setChartList] = useState<API.Chart[]>()
  const [total, setTotal] = useState<number>(0)
  const [loading, setLoading] = useState<boolean>(false)

  /**
   * 获取数据
   */
  const loadData = async () => {
    try {
      const res = await listChartByPageUsingPost(searchParams);
      setLoading(true)
      if (res.data) {
        setChartList(res.data.records ?? [])
        setTotal(res.data.total ?? 0)
        // 净化，不要有标题
        if (res.data.records) {
          res.data.records.forEach(item => {
            if (item.status === 'succeed') {
              const charOption = JSON.parse(item.genChart ?? '{}')
              charOption.title = undefined
              item.genChart = JSON.stringify(charOption)
            }
          })
        }

      }
    } catch (e: any) {
      message.error('获取数据列表错误' + e.message)
    }
    setLoading(false)
  }

  useEffect(() => {
    loadData();
  }, [searchParams])

  return (
    <div className="my-chart">
      <div>
        <Search placeholder="请输入图标名称" enterButton
                onSearch={(value) => {
                  // 设置搜索条件
                  setSearchParams({
                    ...initSearchParams,
                    name: value,
                  })
                }}
        />
      </div>
      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        pagination={{
          onChange: (page) => {
            console.log(page);
            setSearchParams({
              ...searchParams,
              current: page,
            })
          },
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total: total,
        }}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item
            key={item.id}
          >
            <Card>
              <List.Item.Meta
                avatar={<Avatar src={currentUser && currentUser.userAvatar}/>}
                title={item.name}
                description={item.chartType ? ('图表类型:' + item.chartType) : undefined}
              />
              <>
                {
                  item.status === 'succeed' &&
                  <>
                    <div style={{marginBottom: 16}}/>
                    {item.goal}
                    <div style={{marginBottom: 16}}/>
                    <ReactECharts option={item.genChart && JSON.parse(item.genChart)}/>
                  </>
                }
                {
                  item.status === 'wait' &&
                  <>
                    <Result
                      status='info'
                      title='图表待生成'
                      subTitle={item.execMessage ?? '当前图标生成队列繁忙,请耐心等待'}
                    />
                  </>
                }
                {
                  item.status === 'running' &&
                  <>
                    <Result
                      status='info'
                      title='图表生成中'
                      subTitle={item.execMessage}
                    />
                  </>
                }
                {
                  item.status === 'fail' &&
                  <>
                    <Result
                      status='error'
                      title='图表生成失败'
                      subTitle={item.execMessage}
                    />
                  </>
                }
              </>
            </Card>

          </List.Item>
        )}
      />
      total: {total}

    </div>

  );
};
export default MyChart;
